<template>
  <div class="user-list">
    <n-card>
      <template #header>
        <div class="header-actions">
          <span>{{ t('menu.userList') }}</span>
          <div style="display: flex; align-items: center; gap: 8px;">
            <n-button size="small" quaternary @click="resetColumnWidths">
              <template #icon>
                <n-icon><Icons name="refresh-outline" /></n-icon>
              </template>
              重置列宽
            </n-button>
            <n-button type="primary" @click="handleAdd">
              <template #icon>
                <n-icon><AddOutline /></n-icon>
              </template>
              {{ t('common.add') }}
            </n-button>
          </div>
        </div>
      </template>

      <div class="search-form">
        <n-form inline :model="searchForm" :show-label="false">
          <n-form-item>
            <n-input
              v-model:value="searchForm.username"
              :placeholder="t('user.username')"
              clearable
            />
          </n-form-item>
          <n-form-item>
            <n-select
              v-model:value="searchForm.role"
              :placeholder="t('user.role')"
              clearable
              :options="roleOptions"
              style="width: 120px"
            />
          </n-form-item>
          <n-form-item>
            <n-select
              v-model:value="searchForm.status"
              :placeholder="t('common.status')"
              clearable
              :options="statusOptions"
              style="width: 120px"
            />
          </n-form-item>
          <n-form-item>
            <n-button type="primary" @click="handleSearch">
              {{ t('common.search') }}
            </n-button>
            <n-button @click="handleReset" style="margin-left: 8px">
              {{ t('common.reset') }}
            </n-button>
          </n-form-item>
        </n-form>
      </div>

      <n-data-table
        :columns="columns"
        :data="tableData"
        :loading="loading"
        :pagination="pagination"
        :scroll-x="1400"
        :class="{ 'resizing': isResizing }"
        @update:page="handlePageChange"
        @update-page-size = "handlePageSizeChange"
        remote
      />
    </n-card>

    <n-modal v-model:show="showModal" preset="dialog" :title="modalTitle">
      <n-form
        ref="formRef"
        :model="formData"
        :rules="rules"
        label-placement="left"
        label-width="auto"
      >
        <n-form-item :label="t('user.username')" path="username">
          <n-input v-model:value="formData.username" placeholder="请输入用户名" />
        </n-form-item>
        <n-form-item v-if="modalType === 'add'" :label="'密码'" path="password">
          <n-input v-model:value="formData.password" type="password" placeholder="请输入密码" />
        </n-form-item>
        <n-form-item :label="t('user.email')" path="email">
          <n-input v-model:value="formData.email" placeholder="请输入邮箱" />
        </n-form-item>
        <n-form-item v-if="modalType === 'add'" :label="'昵称'" path="nickname">
          <n-input v-model:value="formData.nickname" placeholder="请输入昵称" />
        </n-form-item>
        <n-form-item v-if="modalType === 'add'" :label="'性别'" path="gender">
          <n-select v-model:value="formData.sex" :options="genderOptions" placeholder="请选择性别" />
        </n-form-item>
        <n-form-item v-if="modalType === 'add'" :label="'角色'" path="role">
          <n-select v-model:value="formData.role" :options="addRoleOptions" placeholder="请选择角色" />
        </n-form-item>
        <n-form-item v-if="modalType === 'edit'" :label="t('user.role')" path="role">
          <n-select v-model:value="formData.role" :options="roleOptions"  />
        </n-form-item>
        <n-form-item v-if="modalType === 'edit'" :label="t('user.status')" path="status">
          <n-select v-model:value="formData.status" :options="statusOptions" />
        </n-form-item>
      </n-form>
      <template #action>
        <n-space>
          <n-button @click="showModal = false">
            {{ t('common.cancel') }}
          </n-button>
          <n-button type="primary" @click="handleSave" :loading="saveLoading">
            {{ t('common.save') }}
          </n-button>
        </n-space>
      </template>
    </n-modal>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted, h } from 'vue'
import { useI18n } from 'vue-i18n'
import { useResizableColumns } from '@/composables/useResizableColumns'
import {
  NCard,
  NButton,
  NIcon,
  NForm,
  NFormItem,
  NInput,
  NSelect,
  NDataTable,
  NModal,
  NSpace,
  NAvatar,
  useMessage,
  useDialog
} from 'naive-ui'
import { AddOutline, CreateOutline, TrashOutline, StopCircleOutline, PlayCircleOutline } from '@/components/Icons'
import Icons from '@/components/Icons.vue'
import {userApi, UsersItem} from '@/api'

const { t } = useI18n({ useScope: 'global' })
const message = useMessage()
const dialog = useDialog()

const loading = ref(false)
const saveLoading = ref(false)
const showModal = ref(false)
const modalType = ref<'add' | 'edit'>('add')
const currentUser = ref<any>({})
const formRef = ref()

const searchForm = reactive({
  username: '',
  role: null,
  status: null
})

const formData = reactive({
  username: '',
  password: '',
  email: '',
  nickname: '',
  sex: 1,
  role: 1,
  status: 'active'
})

const tableData = ref<UsersItem[]>([])
const pagination = reactive({
  page: 1,
  pageSize: 5,
  itemCount: 0,
  showSizePicker: true,
  pageSizes: [5, 10, 20, 50],
  showQuickJumper: true,
  prefix: ({ itemCount }: any) => `共 ${itemCount} 条`
  // prefix: ({ itemCount }: any) => t('common.total', { count: itemCount })
})

const modalTitle = computed(() => {
  return modalType.value === 'add' ? t('common.add') : t('common.edit')
})

const roleOptions = [
  { label: '管理员', value: 'admin' },
  { label: '编辑', value: 'editor' },
  { label: '创作者', value: 'creator' },
  { label: '用户', value: 'user' }
]

const statusOptions = computed(() => [
  { label: t('user.status.normal'), value: 'normal' },
  { label: t('user.status.disable'), value: 'disable' },
  { label: t('user.status.underReview'), value: 'underReview' }
])

const genderOptions = [
  { label: '男', value: 1 },
  { label: '女', value: 0 },
  { label: '保密', value: -1 }
]

const addRoleOptions = [
  { label: '普通用户', value: 1 },
  { label: '创作者', value: 2 },
  { label: '管理员', value: 3 }
]

const rules = computed(() => {
  const baseRules = {
    username: {
      required: true,
      message: '请输入用户名',
      trigger: 'blur'
    },
    email: {
      required: true,
      message: '请输入邮箱',
      trigger: 'blur'
    }
  }
  
  if (modalType.value === 'add') {
    return {
      ...baseRules,
      password: {
        required: true,
        message: '请输入密码',
        trigger: 'blur'
      },
      nickname: {
        required: true,
        message: '请输入昵称',
        trigger: 'blur'
      },
      gender: {
        required: true,
        message: '请选择性别',
        trigger: 'change',
        type: 'number',
        validator: (rule: any, value: any) => {
          if (value === null || value === undefined || value === '') {
            return new Error('请选择性别')
          }
          return true
        }
      },
      role: {
        required: true,
        message: '请选择角色',
        trigger: 'change',
        type: 'number',
        validator: (rule: any, value: any) => {
          if (value === null || value === undefined || value === '') {
            return new Error('请选择角色')
          }
          return true
        }
      }
    }
  } else {
    return {
      ...baseRules,
      role: {
        required: true,
        message: '请选择角色',
        trigger: 'change'
      }
    }
  }
})

const getRoleTag = (role: number) => {
      let roleText = ''
      let roleType = 'success'
      switch (role) {
        case 1:
          roleText = '用户'
          roleType = 'error'
          break
        case 2:
          roleText = '创作者'
          roleType = 'warning'
          break
        case 3:
          roleText = '管理员'
          roleType = 'info'
          break
      }
      const buttons = [
        h(NButton, {
          size: 'tiny',
          type: roleType,
          // text: true
        }, { default: () => t(roleText) }),
      ]

      return h('div', buttons)
    }

const getSexTag = (sex: number) => {
  let sexText = ''
  let sexType = 'success'
  switch (sex) {
    case -1:
      sexText = '保密'
      sexType = 'error'
      break
    case 0:
      sexText = '女'
      sexType = 'warning'
      break
    case 1:
      sexText = '男'
      sexType = 'info'
      break
    default:
      sexText = '未知'
  }
  const buttons = [
    h(NButton, {
      size: 'tiny',
      type: sexType,
      // text: true
    }, { default: () => t(sexText) }),
  ]

  return h('div', buttons)
}



const getStatusTag = (status: number) => {
  let statusText = ''
  let statusType = 'success'
  console.log(status)
  switch (status) {
    case 1:
      statusType = 'success'
      statusText = '正常'
      break
    case 0:
      statusType = 'warning'
      statusText = '审核中'
      break
    case -1:
      statusType = 'error'
      statusText = '禁用'
      break
  }

  const buttons = [
    h(NButton, {
      size: 'tiny',
      type: statusType,
      // text: true
    }, { default: () => t(statusText) }),
  ]

  return h('div', buttons)
}

// 基础列配置
const baseColumns = [
  {
    title: 'ID',
    key: 'id',
    width: 60,
    minWidth: 40,
    maxWidth: 100
  },
  {
    title: t('user.username'),
    key: 'username',
    width: 120,
    minWidth: 40,
    maxWidth: 180,
    ellipsis: { tooltip: true },
    render: (row: any) => {
      return h('div', { style: 'display: flex; align-items: center;' }, [
        h(NAvatar, { 
          size: 'small', 
          src: row.avatar,
          fallbackSrc: '/images/default-avatar.svg',
          style: 'margin-right: 8px;',
          onError: () => {
            // 头像加载失败时的处理
            console.log('Avatar load failed for user:', row.username)
          }
        }),
        h('span', row.username)
      ])
    }
  },
  {
    title: t('user.nickname'),
    key: 'nickname',
    width: 180,
    minWidth: 40,
    maxWidth: 250,
    ellipsis: { tooltip: true }
  },
  {
    title: t('user.email'),
    key: 'email',
    width: 180,
    minWidth: 40,
    maxWidth: 250,
    ellipsis: { tooltip: true }
  },
  {
    title: t('user.role'),
    key: 'role',
    width: 100,
    minWidth: 40,
    maxWidth: 120,
    // render: (row: any) =>
    render: (row: any) => getRoleTag(row.role)
  },
  {
    title: t('user.status.title'),
    key: 'status',
    width: 100,
    minWidth: 40,
    maxWidth: 120,
    render: (row: any) => getStatusTag(row.status)
  },
  {
    title: t('user.newsCount'),
    key: 'news_count',
    width: 100,
    minWidth: 40,
    maxWidth: 150
  },
  {
    title: t('user.sex'),
    key: 'sex',
    width: 100,
    minWidth: 40,
    maxWidth: 150,
    render: (row: any) => getSexTag(row.sex)
  },
  {
    title: t('user.registerTime'),
    key: 'created_at',
    width: 160,
    minWidth: 40,
    maxWidth: 200
  },
  {
    title: t('common.operation'),
    key: 'actions',
    width: 200,
    minWidth: 40,
    maxWidth: 280,
    resizable: false,
    render: (row: any) => {
      const buttons = [
        h(NButton, {
          size: 'small',
          type: 'primary',
          onClick: () => handleEdit(row)
        }, { default: () => t('common.edit'), icon: () => h(NIcon, () => h(CreateOutline)) }),
        
        h(NButton, {
          size: 'small',
          type: row.status === 'active' ? 'warning' : 'success',
          onClick: () => handleToggleStatus(row),
          style: { marginLeft: '8px' }
        }, { 
          default: () => row.status === 1 ? '禁用' : '启用',
          icon: () => h(NIcon, () => h(row.status === 1 ? StopCircleOutline : PlayCircleOutline))
        }),
        
        h(NButton, {
          size: 'small',
          type: 'error',
          onClick: () => handleDelete(row),
          style: { marginLeft: '8px' }
        }, { default: () => t('common.delete'), icon: () => h(NIcon, () => h(TrashOutline)) })
      ]
      
      return h('div', buttons)
    }
  }
]

// 使用可调整列宽的Hook
const { resizableColumns, resetColumnWidths, isResizing } = useResizableColumns({
  columns: baseColumns,
  tableKey: 'user-list',
  defaultWidths: {
    'id': 60,
    'username': 120,
    'nickname':100,
    'email': 180,
    'role': 100,
    'status': 100,
    'articlesCount': 100,
    'followersCount': 100,
    'lastLoginTime': 160,
    'actions': 200
  }
})

const columns = computed(() => resizableColumns.value)

const loadData = async () => {
  try {
    loading.value = true
    const params = {
      page: pagination.page - 1, // API页码从0开始，前端从1开始
      rows: pagination.pageSize,
      ...searchForm
    }
    // if (params.page)
    const response = await userApi.getList(params)
    console.log('页面加载的response', response)
    if (response.code === 200 && response.status === 'success' && response.data) {
      tableData.value = response.data.user_list || []
      pagination.itemCount = response.data.total || 0
    }else{
      message.error('加载数据失败')
    }
  } catch (error:any) {
    console.log('加载数据错误',error)
    if (error.status !== 401){
      message.error(error.error || '加载数据失败')
    }

  } finally {
    loading.value = false
  }
}

const handleSearch = () => {
  pagination.page = 1
  loadData()
}
const handlePageSizeChange = (pageSize: number) => {
  console.log('每页条数变化:', { from: pagination.pageSize, to: pageSize })
  pagination.pageSize = pageSize
  pagination.page = 0 // 重置到第一页
  loadData()
}
const handleReset = () => {
  searchForm.username = ''
  searchForm.role = null
  searchForm.status = null
  pagination.page = 1
  loadData()
}

const handlePageChange = (page: number) => {
  pagination.page = page
  loadData()
}

const handleAdd = () => {
  modalType.value = 'add'
  Object.assign(formData, {
    username: '',
    password: '',
    email: '',
    nickname: '',
    gender: 1,
    role: 1,
    status: 1
  })
  showModal.value = true
  // 重置表单验证状态
  setTimeout(() => {
    formRef.value?.restoreValidation()
  }, 0)
}

const handleEdit = (row: any) => {
  modalType.value = 'edit'
  currentUser.value = row
  Object.assign(formData, {
    username: row.username,
    email: row.email,
    role: row.role,
    status: row.status
  })
  showModal.value = true
}

const handleSave = async () => {
  try {
    await formRef.value?.validate()
    saveLoading.value = true
    
    if (modalType.value === 'add') {
      const addUserData = {
        username: formData.username,
        password: formData.password,
        email: formData.email,
        nickname: formData.nickname,
        sex: formData.sex,
        role: formData.role
      }
      const response = await userApi.addUser(addUserData)
      if (response.code === 200 && response.status === 'success') {
        message.success(response.message || '添加用户成功')
      } else {
        message.error(response.message || '添加用户失败')
        return
      }
    } else {
      await userApi.update(currentUser.value.id, formData)
      message.success('更新成功')
    }
    
    showModal.value = false
    await loadData()
  } catch (error: any) {
    console.error('保存失败:', error)
    const errorMessage = error.error || error.message || (modalType.value === 'add' ? '添加用户失败' : '更新失败')
    message.error(errorMessage)
  } finally {
    saveLoading.value = false
  }
}

const handleToggleStatus = async (row: any) => {
  const newStatus = row.status === 'active' ? 'inactive' : 'active'
  const action = newStatus === 'active' ? '启用' : '禁用'
  
  dialog.info({
    title: '确认操作',
    content: `确认${action}用户"${row.username}"吗？`,
    positiveText: t('common.confirm'),
    negativeText: t('common.cancel'),
    onPositiveClick: async () => {
      try {
        await userApi.update(row.id, { status: newStatus })
        message.success(`${action}成功`)
        loadData()
      } catch (error) {
        message.error(`${action}失败`)
      }
    }
  })
}

const handleDelete = (row: any) => {
  dialog.warning({
    title: t('common.confirm'),
    content: `确认删除用户"${row.username}"吗？`,
    positiveText: t('common.confirm'),
    negativeText: t('common.cancel'),
    onPositiveClick: async () => {
      try {
        await userApi.delete(row.id)
        message.success('删除成功')
        await loadData()
      } catch (error) {
        message.error('删除失败')
      }
    }
  })
}

onMounted(() => {
  loadData()
})
</script>

<style scoped>
.header-actions {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.n-tag-info {
  background-color: #4876cd !important;
  border-color: #8ca6db !important;
}
.search-form {
  margin-bottom: 12px;
  margin-top:12px;
  height:65px;
}
</style>